﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AppLimit.CloudComputing.SharpBox;
using AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox;
using System.IO;
namespace CypherBox
{
   public class DropBox
    {
        protected ICloudStorageConfiguration m_Config;
        protected ICloudStorageAccessToken m_Token;
        public ICloudStorageAccessToken Token { get { return m_Token; } }
        protected CloudStorage m_Storage;
        protected ICloudDirectoryEntry m_CurrentDir;
        protected List<string> m_currentPath = new List<string>();
        public string CurrentDirectory { get { return string.Join("/", m_currentPath); } }
        public DropBox(string username, string password)
        {
            m_Storage = new CloudStorage();
            m_Config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
            DropBoxCredentials m_Credentials = new DropBoxCredentials();
            m_Credentials.ConsumerKey = "ax9kcmzsya1n355";
            m_Credentials.ConsumerSecret = "586il9r36yu5pbv";
            m_Credentials.UserName = username;
            m_Credentials.Password = password;
            m_Token = m_Storage.Open(m_Config, m_Credentials);
            m_CurrentDir = m_Storage.GetRoot();
        }
        public void SaveToken(string path)
        {
            Stream tokenstream = m_Storage.SerializeSecurityToken(m_Token);
            Stream tokenfile = new FileStream(path, FileMode.Create);
            tokenstream.CopyTo(tokenfile);
            tokenfile.Close();
        }
        public DropBox(ICloudStorageAccessToken token)
        {
            m_Storage = new CloudStorage();
            m_Config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
            m_Token = m_Storage.Open(m_Config, token);
            m_CurrentDir = m_Storage.GetRoot();
        }
        public void Browse(string name)
        {
            m_CurrentDir = (ICloudDirectoryEntry)m_CurrentDir.GetChild(name);
            m_currentPath.Add(name);
        }
        public void BrowseParent()
        {
            m_CurrentDir = (ICloudDirectoryEntry)m_CurrentDir.Parent;
            m_currentPath.RemoveAt(m_currentPath.Count-1);
        }
        public string[] GetChildDirectories()
        {
            var r = from entry in m_CurrentDir
                    where entry is ICloudDirectoryEntry
                    select entry.Name;
            return r.ToArray<string>();
        }
        public string[] GetFiles()
        {
            var r = from entry in m_CurrentDir
                    where !(entry is ICloudDirectoryEntry)
                    select entry.Name;
            return r.ToArray<string>();
        }
        public void Close()
        {
            m_Storage.Close();
        }

    }
}
